<template>
  <div class="page">
    <div class="top">
      <div class="header">
        <a href="/">
          <img src="/favicon.svg" class="logo" alt="logo" />
          <span class="title">chaos saas</span>
        </a>
      </div>
    </div>

    <div class="main">
      <a-form
        id="formLogin"
        class="user-layout-login"
        ref="formLogin"
        :model="formState"
        @finish="handleSubmit"
      >
        <a-form-item name="tenantId" :rules="tenantIdRules">
          <a-select
            size="large"
            placeholder="请选择租户"
            v-model:value="formState.tenantId"
            @change="doTenantChange"
          >
            <a-select-option v-for="tenant in tenants" :key="tenant.id" :value="tenant.id">
              {{ tenant.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-alert
          v-if="isLoginError"
          type="error"
          showIcon
          style="margin-bottom: 24px"
          message="用户名密码错误"
        />
        <a-form-item name="username" :rules="usernameRules">
          <a-input
            size="large"
            type="text"
            placeholder="请输入用户名"
            v-model:value="formState.username"
          >
            <template #prefix>
              <a-icon type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item name="password" :rules="passwordRules">
          <a-input-password
            size="large"
            placeholder="请输入密码"
            v-model:value="formState.password"
          >
            <template #prefix>
              <a-icon type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
            </template>
          </a-input-password>
        </a-form-item>
        <a-form-item style="margin-top: 24px">
          <a-button
            size="large"
            type="primary"
            htmlType="submit"
            class="login-button"
            :loading="loginBtn"
            :disabled="loginBtn"
          >
            登录
          </a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { message, notification } from 'ant-design-vue';
import { getByData, getData, list, login } from '@/services';
import { useTenantStore } from '@/stores/global';

const router = useRouter();
const formLogin = ref(null);
const isLoginError = ref(false);
const loginBtn = ref(false);

const formState = reactive({
  username: '',
  password: '',
  tenantId: '',
});
const tenants = ref([]);
const fetchTenants = async () => {
  const response = await list('/api/auth/tTenant');
  tenants.value = response.list;
};
onMounted(() => {
  fetchTenants();
});

const usernameRules = [{ required: true, message: '用户名必填', trigger: 'change' }];

const passwordRules = [{ required: true, message: '密码必填', trigger: 'blur' }];

const tenantIdRules = [{ required: true, message: '请选择租户', trigger: 'change' }];

const clientDetails = ref({});
const authorizedGrantTypes = 'admin_username';
const tenantStore = useTenantStore();

const doTenantChange = async (value: string) => {
  const tenantId = value;
  tenantStore.setTenantId(value);
  await localStorage.setItem('enterprise_code', getEnterpriseCodeByTenantId(tenantId));

  const clientDetailsData = await getByData('/api/auth/oauthClientDetails/saas', {
    tenantId,
    authorizedGrantTypes,
  });
  clientDetails.value = clientDetailsData.data;
};
const getEnterpriseCodeByTenantId = (tenantId: number): string | undefined => {
  const tenant = tenants.value.find(t => t.id === tenantId);
  return tenant ? tenant.enterpriseCode : '';
};

const dealInfo = async () => {
  const res = await getData('/api/elog/tenant/checkServiceValidity');
  if (res) {
    message.warn('系统服务有效期有足1个月，请及时续约');
  }
};

const handleSubmit = () => {
  loginBtn.value = true;

  formLogin.value
    .validateFields()
    .then(async values => {
      const loginParams = { ...values };
      const username = loginParams.username;
      const password = loginParams.password;
      const tenantId = loginParams.tenantId;

      const { success, msg, data } = await login({
        username,
        password,
        tenantId,
        client_id: clientDetails.value.clientId,
        client_secret: clientDetails.value.clientSecret,
        grant_type: authorizedGrantTypes,
      });

      if (success) {
        localStorage.setItem('access_token', data.access_token);
        localStorage.setItem('username', data.username);

        await router.push({ path: '/' });
        // 延迟 1 秒显示欢迎信息
        setTimeout(() => {
          notification.success({
            message: '欢迎',
            description: `欢迎回来`,
          });

          dealInfo();
        }, 1000);
      } else {
        isLoginError.value = true;
        loginBtn.value = false;
        notification.error({
          message: '登录失败',
          description: msg,
        });
      }
    })
    .catch(err => {
      setTimeout(() => {
        loginBtn.value = false;
      }, 600);
    });
};
</script>

<style lang="less" scoped>
.page {
  height: 100vh;
  background-color: #f0f2f5;
  background-image: url('https://preview.pro.antdv.com/assets/background.ebcb9160.svg');

  .top {
    padding: 132px 0 24px;

    text-align: center;

    .header {
      height: 44px;
      line-height: 44px;

      .badge {
        position: absolute;
        display: inline-block;
        line-height: 1;
        vertical-align: middle;
        margin-left: -12px;
        margin-top: -10px;
        opacity: 0.8;
      }

      .logo {
        height: 44px;
        vertical-align: top;
        margin-right: 16px;
        border-style: none;
      }

      .title {
        font-size: 33px;
        color: rgba(0, 0, 0, 0.85);
        font-family: Avenir, 'Helvetica Neue', Arial, Helvetica, sans-serif;
        font-weight: 600;
        position: relative;
        top: 2px;
      }
    }

    .desc {
      font-size: 14px;
      color: rgba(0, 0, 0, 0.45);
      margin-top: 12px;
      margin-bottom: 40px;
    }
  }

  .main {
    display: flex;
    justify-content: center;
    align-items: center;

    .user-layout-login {
      width: 368px;
      padding: 32px 40px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

      .ant-form-item {
        margin-bottom: 24px;
      }

      .ant-alert {
        margin-bottom: 24px;
      }

      .ant-input-affix-wrapper {
        &.ant-input-affix-wrapper-lg {
          height: 40px;
        }
      }

      .login-button {
        width: 100%;
        height: 40px;
        font-size: 16px;
      }
    }
  }
}
</style>
